package com.situ.mall.notification.api.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.notification.spi.model.Notification;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface NotificationMapper extends BaseMapper<Notification> {
    default Page<Notification> findAll(Page<Notification> page,Notification notification){
        LambdaQueryWrapper<Notification> queryWrapper=new LambdaQueryWrapper<>(notification);
        return this.selectPage(page,queryWrapper);
    }

    // 查询用户的通知列表
    default Page<Notification> findUserNotifications(Page<Notification> page, Integer userId) {
        LambdaQueryWrapper<Notification> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Notification::getUserId, userId)
                .eq(Notification::getIsDel, 0)
                .orderByDesc(Notification::getCreatedTime);
        return this.selectPage(page, queryWrapper);
    }

    // 获取用户未读通知数量
    default Integer getUnreadNotificationCount(Integer userId) {
        LambdaQueryWrapper<Notification> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Notification::getUserId, userId)
                .eq(Notification::getIsRead, 0)
                .eq(Notification::getIsDel, 0);
        return Math.toIntExact(this.selectCount(queryWrapper));
    }

    // 标记通知为已读
    default boolean markNotificationAsRead(Integer notificationId) {
        LambdaUpdateWrapper<Notification> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Notification::getId, notificationId)
                .set(Notification::getIsRead, 1)
                .set(Notification::getReadTime, LocalDateTime.now());
        return this.update(null, updateWrapper) > 0;
    }

    // 标记用户所有通知为已读
    default boolean markAllNotificationsAsRead(Integer userId) {
        LambdaUpdateWrapper<Notification> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Notification::getUserId, userId)
                .eq(Notification::getIsRead, 0)
                .eq(Notification::getIsDel, 0)
                .set(Notification::getIsRead, 1)
                .set(Notification::getReadTime, LocalDateTime.now());
        return this.update(null, updateWrapper) > 0;
    }
}
